package com.example.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

//SqlSessionFactoryBuilder.builder() --> SqlSessionFactory.(openSeession) --> SqlSession
public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        // 导入maybatis-config文件,使用SqlSessionFactoryBuilder创建sessionFactory
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //封装创建sqlSession的方法
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
} 
